<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <!-- 搜索 -->
        <el-row>
          <el-col class="top_title">
            <span>说明：目前支持学科和关键字条件筛选</span>
            <el-button
              type="success"
              size="small"
              icon="el-icon-edit"
              @click="$router.push('new')"
              >新增试题</el-button
            >
          </el-col>
        </el-row>
        <!-- 搜索 -->
        <el-form :model="form" label-width="80px">
          <el-row>
            <!-- 学科 -->
            <el-col :span="6">
              <el-form-item label="学科">
                <el-select
                  style="width: 100%"
                  v-model="form.subjectID"
                  placeholder="请选择"
                  @change="onSubjectChange"
                >
                  <el-option
                    v-for="item in subjects"
                    :key="item.id"
                    :label="item.subjectName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 目录 -->
            <el-col :span="6">
              <el-form-item label="二级目录">
                <el-select
                  style="width: 100%"
                  v-model="form.catalogID"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in directory"
                    :key="item.id"
                    :label="item.directoryName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 标签 -->
            <el-col :span="6">
              <el-form-item label="标签">
                <el-select
                  style="width: 100%"
                  v-model="form.tags"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in tagList"
                    :key="item.id"
                    :label="item.tagName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 关键字 -->
            <el-col :span="6">
              <el-form-item label="关键字">
                <el-input
                  v-model="form.keyword"
                  placeholder="根据题干搜索"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <!-- 试题类型 -->
            <el-col :span="6">
              <el-form-item label="试题类型">
                <el-select
                  style="width: 100%"
                  v-model="form.questionType"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in questionType"
                    :key="item.id"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 难度 -->
            <el-col :span="6">
              <el-form-item label="难度">
                <el-select
                  class="filter-item"
                  style="width: 100%"
                  v-model="form.difficulty"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in difficulty"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <!-- 方向 -->
            <el-col :span="6">
              <el-form-item label="方向">
                <el-select
                  style="width: 100%"
                  v-model="form.direction"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in direction"
                    :key="item.value"
                    :label="item"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 录入人 -->
            <el-col :span="6">
              <el-form-item label="录入人">
                <el-select
                  style="width: 100%"
                  v-model="form.creatorID"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="(item, i) in userList"
                    :key="i"
                    :label="item.username"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <!-- 题目备注 -->
            <el-col :span="6">
              <el-form-item label="题目备注">
                <el-input v-model="form.remarks"></el-input>
              </el-form-item>
            </el-col>
            <!-- 企业简称 -->
            <el-col :span="6">
              <el-form-item label="企业简称">
                <el-input v-model="form.shortName"></el-input>
              </el-form-item>
            </el-col>
            <!-- 城市 -->
            <el-col :span="8">
              <el-form-item label="城市">
                <MyCity v-model="provAndCity" />
              </el-form-item>
            </el-col>

            <el-col :span="3" style="text-align: right">
              <el-button @click="clear" size="small">清除</el-button>
              <el-button size="small" type="primary" @click="search">
                搜索</el-button
              >
            </el-col>
          </el-row>
        </el-form>
        <!-- 动态切换 -->
        <el-tabs
          v-model="activeName"
          type="card"
          @tab-click="handleClick"
          style="margin-top: 10px; margin-bottom: -10px"
        >
          <el-tab-pane label="全部" name="first"></el-tab-pane>
          <el-tab-pane label="待审核" name="second"></el-tab-pane>
          <el-tab-pane label="已审核" name="third"></el-tab-pane>
          <el-tab-pane label="已拒绝" name="fourth"></el-tab-pane>
        </el-tabs>
        <!-- 数据记录 共计多少条数据-->
        <el-alert
          v-if="cResultTip"
          :title="cResultTip"
          type="info"
          class="alert"
          :closable="false"
          show-icon
        ></el-alert>
        <!-- end -->
        <!-- 数据列表 -->
        <el-table :data="data" fit highlight-current-row style="width: 100%">
          <el-table-column align="center" label="试题编码" width="140">
            <template slot-scope="scope">
              <span>{{ scope.row.number }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="学科" width="140">
            <template slot-scope="scope">
              <span>{{ scope.row.subject }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="目录" width="140">
            <template slot-scope="scope">
              <span>{{ scope.row.catalog }}</span>
            </template>
          </el-table-column>
          <el-table-column label="题型" width="140">
            <template slot-scope="scope">
              <span>{{ formquestionType(scope.row.questionType) }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="题干" width="230">
            <template slot-scope="scope">
              <span v-html="scope.row.question"></span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="录入时间" width="160">
            <template slot-scope="scope">
              <span>{{ scope.row.addDate | dateFormat }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="难度" width="140">
            <template slot-scope="scope">
              <span>{{ formdifficulty(scope.row.difficulty) }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="录入人" width="140">
            <template slot-scope="scope">
              <span>{{ scope.row.creator }}</span>
            </template>
          </el-table-column>
          <!-- 审核状态 -->
          <el-table-column align="center" label="审核状态" width="140">
            <template slot-scope="scope">
              <span v-if="scope.row.chkState == 0">待审核</span>
              <span v-if="scope.row.chkState == 1">通过</span>
              <span v-if="scope.row.chkState == 2">拒绝</span>
            </template>
          </el-table-column>
          <!-- 审核意见 -->
          <el-table-column align="center" label="审核意见" width="160">
            <template slot-scope="scope">
              <span>{{ scope.row.chkRemarks }}</span>
            </template>
          </el-table-column>
          <!-- 审核人 -->
          <el-table-column align="center" label="审核人" width="140">
            <template slot-scope="scope">
              <span>{{ scope.row.chkUser }}</span>
            </template>
          </el-table-column>
          <!--发布状态  -->
          <el-table-column align="center" label="发布状态" width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.publishState == 0">下架</span>
              <span v-else>上架</span>
            </template>
          </el-table-column>
          <!-- 操作按钮 -->
          <el-table-column
            align="center"
            fixed="right"
            label="操作"
            width="200"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="showPreview(scope.row)"
                >预览</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="auditing(scope.row.id)"
                :disabled="scope.row.chkState === 0 ? false : true"
                >审核</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="$router.push(`new?id=${scope.row.id}`)"
                :disabled="scope.row.publishState === 1 ? false : true"
                >修改</el-button
              >
              <el-button type="text" size="small" @click="putaway(scope.row)">
                {{ scope.row.publishState === 0 ? "下架" : "上架" }}
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="del(scope.row.id)"
                :disabled="scope.row.publishState === 1 ? false : true"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- end -->
        <!-- 分页 -->
        <div class="pagination" v-show="total">
          <div class="pages">
            <el-pagination
              background
              @size-change="hSizeChange"
              @current-change="hCurrentChange"
              :current-page="Number(form.page)"
              :total="Number(total)"
              :page-size="Number(form.pagesize)"
              :page-sizes="[2, 5, 10, 20, 50]"
              layout="sizes, prev, pager, next, jumper"
            ></el-pagination>
          </div>
        </div>
        <!-- end -->
      </el-card>
    </div>
    <!-- 弹窗 -->
    <el-dialog
      title="题目审核"
      :visible.sync="isShowDialog"
      width="18%"
      @close="close"
    >
      <el-form :model="form">
        <el-form-item>
          <el-radio v-model="params.chkState" :label="1">通过</el-radio>
          <el-radio v-model="params.chkState" :label="2">拒绝</el-radio>
        </el-form-item>
        <el-form-item>
          <el-input
            type="textarea"
            v-model.trim="params.chkRemarks"
            placeholder="请输入审核意见"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <template>
        <div style="text-align: right">
          <el-button @click="isShowDialog = false">取消</el-button>
          <el-button type="primary" @click="submit()">确认</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 引入封装的预览弹出层组件 -->
    <Preview
      ref="pr"
      :show-dialog.sync="showDialog"
      :question-detail.sync="questionDetail"
    />
  </div>
</template>

<script>
// 引入预览弹出层组件
import Preview from '@/module-hmmm/components/questions-preview.vue'
import { difficulty, questionType, direction, status } from '@/api/hmmm/constants'
// 学科列表数据
import { list } from '@/api/hmmm/subjects'
// 引入用户列表
import { list as user } from '@/api/base/users'
// 标签列表
import { list as tags } from '@/api/hmmm/tags'
// 目录
import { list as directory } from '@/api/hmmm/directorys'
// 引入题型列表接口
import { choice, remove, choicePublish, choiceCheck } from '@/api/hmmm/questions'
// 城市
import MyCity from './companys/citys.vue'
export default {
  name: 'QuestionsChoice',
  components: {
    Preview,
    MyCity
  },
  data () {
    return {
      // 学科列表数据
      subjects: [],
      // 目录
      catalog: [],
      // 录入人列表
      userList: [],
      // 目录
      directory: [],
      // 标签
      tagList: [],
      // 传递给详情页用于获取详情页数据
      questionDetail: {},
      // 控制弹出层显示隐藏
      showDialog: false,
      // 题库列表数据
      data: [],
      // 动态切换默认选中
      activeName: 'first',
      total: 0,
      // 城市相关信息
      provAndCity: {
        province: null,
        city: null
      },
      // 查询表单中的参数
      form: {
        // 企业简称
        shortName: null,
        // 状态
        state: null,
        tags: null, // 标签
        catalogID: null, // 二级目录
        subjectID: null, // 学科
        questionType: null, // 试题类型
        direction: null, // 方向
        // 关键字
        keyword: null,
        // 录入人
        creatorID: null,
        // 题目备注
        remarks: null,
        difficulty: null, // 难度
        page: 1, // 页码
        pagesize: 5, // 每页条数
        chkState: null // 审核
      },
      isShowDialog: false,
      params: {
        id: '', // id
        chkState: 1, // 通过/拒绝
        chkRemarks: ''// 文本框
      }
    }
  },
  // 创建完毕,做一次查询
  created () {
    // 获取精选列表
    this.getQuestion()
    // 获取学科
    this.getSubject()
    // 获取录入人
    this.getCreator()
    // 获取标签
    // this.getTagList()//页面一刷新数据就加载下来了
    // console.log('父组件实例', this.$parent.$parent)
  },
  computed: {
    cResultTip () {
      return `共 ${this.total} 条记录`
    },
    status () {
      return status
    },
    direction () {
      return direction
    },
    difficulty () {
      return difficulty
    },
    questionType () {
      return questionType
    }
  },

  methods: {
    // 获取题目列表数据
    async getQuestion () {
      const { data } = await choice({ ...this.form, ...this.provAndCity })
      // console.log('222', data)
      this.total = data.counts
      this.data = data.items
    },
    // 搜索
    search () {
      this.form.page = 1
      this.getQuestion()
    },
    // async search () {
    //   // 子组件的keyword给父组件keyWords
    //   // this.$emit('update:keyWord', this.form.keyword)
    //   // // 异步操作 渲染数据
    //   // await this.$parent.$parent.getQuestion()
    //   // this.$emit('update:page', this.form.page)
    //   // this.form.keyword = ''
    // },
    // 清除表单数据
    clear () {
      for (const key in this.form) {
        if (key === 'page' || key === 'pagesize') {
          continue
        }
        this.form[key] = null
      }
      this.provAndCity = {
        province: '',
        city: ''
      }
      this.tagList = this.directory = []
    },
    // 获取学科数据
    async getSubject () {
      const { data } = await list()
      console.log('学科信息', data)
      this.subjects = data.items
    },
    //  获取录入人
    async getCreator () {
      try {
        const { data: res } = await user()
        // console.log('录入人', res)
        this.userList = res.list
      } catch (error) { }
    },
    //  学科选择框发生变化后触发的函数
    async onSubjectChange (val) {
      this.form.catalogID = null
      this.form.tags = null
      const { data: res } = await directory({ subjectID: val })
      this.directory = res.items
      console.log('目录', this.directory)
      // 获取标签
      this.getTagList()
    },
    //  获取标签列表
    async getTagList () {
      const { data: res } = await tags({
        subjectID: this.form.subjectID
      })
      this.tagList = res.items
      console.log('标签列表', this.tagList)
    },
    // 动态切换栏
    handleClick (tab) {
      if (tab.name === 'first') {
        this.form.chkState = null
        this.getQuestion()
      } else if (tab.name === 'second') {
        this.form.chkState = 0
        this.getQuestion()
      } else if (tab.name === 'third') {
        this.form.chkState = 1
        this.getQuestion()
      } else {
        this.form.chkState = 2
        this.getQuestion()
      }
    },
    // 点击预览展示弹出层
    async showPreview (item) {
      this.showDialog = true
      this.questionDetail = item
      // 执行$nextTick()，DOM更新之后再调用子组件方法=>解决了500的错误
      await this.$nextTick()
      // 调用子组件的获取问题详情的方法
      this.$refs.pr.getQuestionsDetail()
    },
    // 审核弹窗表单数据
    async submit () {
      // 判断文本框是否为空
      if (this.params.chkRemarks === '') {
        return this.$message({
          showClose: true,
          message: '请输入审核意见！',
          type: 'warning'
        })
      }
      const res = await choiceCheck(this.params)
      if (res.status === 200) {
        this.$message.success('操作成功')
        this.isShowDialog = false
        this.getQuestion()
        // 清空上次操作数据 重置
        this.params.id = ''
        this.params.chkRemarks = ''
        this.params.chkState = 1
      }
    },
    // 审核弹层
    close () {
      this.isShowDialog = false
    },
    // 上架
    putaway (row) {
      console.log('上架', row)
      const tip = '您确定要' + (row.publishState === 1 ? '上架' : '下架') + '吗?'
      this.$confirm(tip, '提示', {
        type: 'warning'
      })
        .then(async () => {
          // 手动修改数据
          if (row.publishState === 0) {
            row.publishState = 1
          } else {
            row.publishState = 0
          }
          const res = await choicePublish(row)
          console.log('上架', res)
          this.$message.success('操作成功!')
          this.$nextTick(() => {
            this.getQuestion()
          })
        })
        .catch(() => {
          this.$message.info('已取消操作!')
        })
    },
    // 审核
    auditing (id) {
      this.isShowDialog = true
      this.params.id = id
    },
    // 删除
    del (id) {
      this.$confirm('此操作将永久删除该题目，是否继续？', '提示', { type: 'warning' }).then(async () => {
        await remove({ id })
        this.$message.success('删除成功')
        const newPage = Math.ceil((this.total - 1) / this.form.pagesize)
        if (newPage > 0) {
          this.form.page = this.form.page > newPage ? newPage : this.form.page
        }
        // 刷新列表
        this.getQuestion()
      }).catch(() => {
        this.$message.info('已取消操作!')
      })
    },
    // 格式化枚举-难度
    formdifficulty (type) {
      // console.log('11:', type)
      // 映射关系
      const maps = {}
      difficulty.forEach(item => {
        maps[item.value] = item.label
      })
      // console.log(maps)
      return maps[type]
    },
    // 格式化枚举-题型
    formquestionType (type) {
      // console.log('11:', type)
      // 映射关系
      const maps = {}
      questionType.forEach(item => {
        maps[item.value] = item.label
      })
      // console.log(maps)
      return maps[type]
    },

    // 更改每页显示的条数
    hSizeChange (val) {
      this.form.pagesize = val
      if (this.form.pagesize === val) {
        this.form.page = 1
        this.getQuestion()
      }
    },
    // 点击某一个页码
    hCurrentChange (curPage) {
      this.form.page = curPage
      this.getQuestion()
    }
  }
}
</script>
<style  lang="scss" scoped>
.top_title {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  span {
    font-size: 12px;
    color: pink;
  }
}
.alert {
  margin: 10px 0px;
}
.pagination {
  margin-top: 10px;
  text-align: right;
}
</style>

<style>
.el-table th {
  background-color: #fafafa;
}
.el-table th.is-leaf {
  border-bottom: 2px solid #e8e8e8;
}
.disabled td {
  background-color: #f9f9f9;
  color: #c1c1c1;
}
.disabled .el-button--primary,
.disabled .el-button--danger {
  background-color: #dbdada;
  border: 1px solid #dbdada;
  color: #999;
  cursor: not-allowed;
}
.app-container {
  padding: 10px;
}
</style>
